/**
 * 角色管理页面
 */
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import request from '@/utils/request';
import { useTranslation } from '@/utils/i18n'
import { useThemeStore } from '@/stores/themeStore'
interface RoleData {
  _id?: string;
  id?: number;
  name: string;
  age: number;
  sex: '男' | '女';
  status: '启用' | '禁用';
  createTime: Date | string;
  updateTime: Date | string;
}

interface NewRoleFormData {
  name: string;
  age: number;
  sex: '男' | '女';
  status?: '启用' | '禁用';
}



const RoleManage: React.FC = () => {
    const { t } = useTranslation()
  const themePreference = useThemeStore((state) => state.theme)
  const isDark = useMemo(() => {
    if (themePreference === 'dark') return true
    if (themePreference === 'light') return false
    return window.matchMedia('(prefers-color-scheme: dark)').matches
  }, [themePreference])
  const containerClass = `flex flex-col min-h-screen px-6 py-6 transition-colors ${isDark ? 'bg-slate-900 text-slate-100' : 'bg-white text-gray-900'}`
  const cardClass = `flex-1 rounded-lg shadow px-6 py-6 transition-colors ${isDark ? 'bg-slate-800/90' : 'bg-white'}`
  // 角色数据
  const [roles, setRoles] = useState<RoleData[]>([]);
  const [loading, setLoading] = useState(true);
  const [searchKeyword, setSearchKeyword] = useState('');
  // 分页状态
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize] = useState(5);
  const [totalCount, setTotalCount] = useState(0);
  
  // 格式化日期时间
  const formatDateTime = (dateString: string): string => {
    const date = new Date(dateString);
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
  };
  
  // 获取角色列表 - 使用useCallback避免不必要的重渲染
  const fetchRoles = useCallback(async (pageNum: number = currentPage) => {
    try {
      setLoading(true);
      // 直接传递参数，不嵌套在params对象中
      const response = await request.get('/api/hzl/list', {
        pageNum,
        pageSize
      });
      // 格式化日期并转换为前端需要的数据结构
      const formattedRoles = response.data.list.map((role: { _id?: string; id?: number; name: string; age: number; sex: '男' | '女'; status?: '启用' | '禁用'; createTime: Date | string; updateTime: Date | string; }) => ({
        ...role,
        id: role._id || String(role.id),
        createTime: formatDateTime(new Date(role.createTime).toISOString()),
        updateTime: formatDateTime(new Date(role.updateTime).toISOString())
      }));
      // 确保状态字段存在，默认为启用
      const rolesWithStatus = formattedRoles.map(role => ({
        ...role,
        status: role.status || '启用'
      }));
      setRoles(rolesWithStatus);
      setTotalCount(response.data.total);
      setCurrentPage(pageNum);
    } catch (error: unknown) {
      console.error('获取角色列表失败:', error);
    } finally {
      setLoading(false);
    }
  }, [currentPage, pageSize]); // 只依赖于currentPage和pageSize
  
  // 初始化时执行一次数据加载
  useEffect(() => {
    fetchRoles();
  }, [fetchRoles]); // 添加fetchRoles到依赖项中，确保函数变化时重新执行

  // 控制新增模态框的显示
  const [isAddModalOpen, setIsAddModalOpen] = useState(false);
  
  // 新增表单数据
  const [newRoleData, setNewRoleData] = useState<NewRoleFormData>({
    name: '',
    age: 20,
    sex: '男',
    status: '启用'
  });
  
  // 控制编辑模态框的显示
  const [isEditModalOpen, setIsEditModalOpen] = useState(false);
  
  // 当前编辑的角色ID
  const [currentEditId, setCurrentEditId] = useState<string>('');
  
  // 编辑表单数据
  const [editRoleData, setEditRoleData] = useState<NewRoleFormData>({
    name: '',
    age: 20,
    sex: '男',
    status: '启用'
  });
  
  // 使用已有的formatDateTime函数

  // 打开新增模态框
  const handleOpenAddModal = () => {
    setIsAddModalOpen(true);
    // 重置表单数据
    setNewRoleData({
      name: '',
      age: 20,
      sex: '男'
    });
  };

  // 关闭新增模态框
  const handleCloseAddModal = () => {
    setIsAddModalOpen(false);
  };

  // 处理表单输入变化
  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setNewRoleData(prev => ({
      ...prev,
      [name]: value
    }));
  };



  // 提交新增表单
  const handleSubmitAdd = async () => {
    // 验证表单
    if (!newRoleData.name.trim()) {
      alert(t('role.nameRequired'));
      return;
    }

    if (newRoleData.age < 0 || newRoleData.age > 150) {
      alert(t('role.ageInvalid'));
      return;
    }

    try {
      // 调用后端API添加角色
      await request.post('/api/hzl/add', newRoleData);
      
      // 重新获取角色列表，确保数据一致性
      await fetchRoles(1); // 添加成功后返回第一页
      
      // 关闭模态框
      setIsAddModalOpen(false);
      
      alert(t('role.addSuccess'));
    } catch (error: unknown) {
      console.error('添加角色失败:', error);
      alert(t('role.addFailed'));
    }
  };

  // 修改角色
  const handleEdit = (id: string) => {
    const roleToEdit = roles.find(role => role.id === id);
    if (roleToEdit) {
      setCurrentEditId(id);
      setEditRoleData({
        name: roleToEdit.name,
        age: roleToEdit.age,
        sex: roleToEdit.sex,
        status: roleToEdit.status
      });
      setIsEditModalOpen(true);
    }
  };
  
  // 关闭编辑模态框
  const handleCloseEditModal = () => {
    setIsEditModalOpen(false);
  };
  
  // 处理编辑表单输入变化
  const handleEditInputChange = (e: React.ChangeEvent<HTMLInputElement | HTMLSelectElement>) => {
    const { name, value } = e.target;
    setEditRoleData(prev => ({
      ...prev,
      [name]: value
    }));
  };
  
  // 处理编辑表单年龄变化
  const handleEditAgeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEditRoleData(prev => ({
      ...prev,
      age: parseInt(e.target.value) || 0
    }));
  };
  
  // 提交编辑表单
  const handleSubmitEdit = async () => {
    // 验证表单
    if (!editRoleData.name.trim()) {
      alert(t('role.nameRequired'));
      return;
    }

    if (editRoleData.age < 0 || editRoleData.age > 150) {
      alert(t('role.ageInvalid'));
      return;
    }

    try {
      // 调用后端API更新角色
      await request.put(`/api/hzl/update/${currentEditId}`, editRoleData);
      
      // 刷新当前页面数据，确保数据一致性
      await fetchRoles(currentPage);
      
      // 关闭模态框
      setIsEditModalOpen(false);
      
      alert(t('role.updateSuccess'));
    } catch (error) {
      console.error('更新角色失败:', error);
      alert(t('role.updateFailed'));
    }
  };

  // 删除角色
  const handleDelete = async (id: string) => {
    if (window.confirm(t('role.confirmDelete'))) {
      try {
        // 调用后端API删除角色
        await request.delete(`/api/hzl/delete/${id}`);
        
        // 刷新当前页面数据，确保数据一致性
        await fetchRoles(currentPage);
        
        alert(t('role.deleteSuccess'));
      } catch (error) {
        console.error('删除角色失败:', error);
        alert(t('role.deleteFailed'));
      }
    }
  };
  
  // 批量删除相关状态和函数
  const [selectedIds, setSelectedIds] = useState<string[]>([]);
  
  // 处理单行选择
  const handleRowSelect = (id: string, checked: boolean) => {
    if (checked) {
      setSelectedIds(prev => [...prev, id]);
    } else {
      setSelectedIds(prev => prev.filter(itemId => itemId !== id));
    }
  };
  
  // 处理全选/取消全选
  const filteredRoles = React.useMemo(() => {
    if (!searchKeyword.trim()) {
      return roles;
    }
    const keyword = searchKeyword.trim().toLowerCase();
    return roles.filter((role) => role.name.toLowerCase().includes(keyword));
  }, [roles, searchKeyword]);

  const handleSelectAll = (checked: boolean) => {
    if (checked) {
      setSelectedIds(filteredRoles.map(role => role.id));
    } else {
      setSelectedIds([]);
    }
  };
  
  // 判断是否全选
  const isAllSelected = filteredRoles.length > 0 && filteredRoles.every((role) => selectedIds.includes(role.id));

  const getGenderLabel = (gender: RoleData['sex']) =>
    gender === '男' ? t('role.gender.male') : t('role.gender.female');

  const getStatusLabel = (status: RoleData['status']) =>
    status === '启用' ? t('role.status.enabled') : t('role.status.disabled');
  
  // 批量删除
  const handleBatchDelete = async () => {
    if (selectedIds.length === 0) {
      alert(t('role.batchDeleteEmpty'));
      return;
    }
    
    if (window.confirm(t('role.batchDeleteConfirm', { count: selectedIds.length }))) {
      try {
        // 调用后端API批量删除角色
        await request.post('/api/hzl/batchDelete', { ids: selectedIds });
        
        // 刷新当前页面数据，确保数据一致性
        await fetchRoles(currentPage);
        // 清空选中状态
        setSelectedIds([]);
        
        alert(t('role.batchDeleteSuccess'));
      } catch (error) {
        console.error('批量删除角色失败:', error);
        alert(t('role.batchDeleteFailed'));
      }
    }
  };

  return (
    <div className={containerClass}>
      <div className="mb-6">
        <h2 className="text-2xl font-bold text-gray-800 dark:text-slate-100">{t('role.title')}</h2>
        <p className="text-gray-500 dark:text-slate-400 mt-1">{t('role.subtitle')}</p>
      </div>
      
      <div className={cardClass}>
        {/* 操作栏：搜索框、批量删除按钮和新增按钮 */}
          <div className="mb-4 flex justify-between items-center">
            {/* 搜索框 */}
            <div className="relative">
              <div className="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                <svg xmlns="http://www.w3.org/2000/svg" className="h-5 w-5 text-gray-400 dark:text-slate-400" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                </svg>
              </div>
              <input
                type="text"
                placeholder={t('role.searchPlaceholder')}
                value={searchKeyword}
                onChange={(e) => setSearchKeyword(e.target.value)}
                className="pl-10 pr-4 py-2 border border-gray-300 dark:border-slate-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 dark:focus:border-slate-400 w-64 bg-white dark:bg-slate-700 text-gray-900 dark:text-slate-100 placeholder-gray-400 dark:placeholder-slate-300 transition-colors"
              />
            </div>
            
            <div className="flex items-center space-x-3">
              {/* 批量删除按钮 */}
              <button
                onClick={handleBatchDelete}
                disabled={selectedIds.length === 0}
                className={`px-4 py-2 rounded-md transition-colors duration-150 flex items-center ${selectedIds.length === 0 ? 'bg-gray-300 text-gray-500 cursor-not-allowed' : 'bg-red-600 text-white hover:bg-red-700'}`}
              >
                <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                </svg>
                {t('role.batchDelete')}
              </button>
              
              {/* 新增按钮 */}
              <button
                onClick={handleOpenAddModal}
                className="bg-blue-600 text-white px-4 py-2 rounded-md hover:bg-blue-700 transition-colors duration-150 flex items-center"
              >
                <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4 mr-2" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 4v16m8-8H4" />
                </svg>
                {t('role.create')}
              </button>
            </div>
          </div>

        {/* 表格 */}
        <div className="overflow-x-auto">
          {loading ? (
            <div className="flex justify-center items-center py-12 text-gray-500">
              {t('common.loading')}
            </div>
          ) : (
            <table className={`min-w-full divide-y divide-gray-200 dark:divide-slate-700 transition-colors ${isDark ? '' : 'bg-white'}`}>
              <thead className={`${isDark ? 'bg-slate-900/70 text-slate-100' : 'bg-slate-200 text-slate-700'} transition-colors`}>
                <tr>
                  <th scope="col" className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider">
                    <input
                      type="checkbox"
                      checked={isAllSelected}
                      onChange={(e) => handleSelectAll(e.target.checked)}
                      className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                    />
                  </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider">
                  {t('role.table.id')}
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider">
                  {t('role.table.name')}
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider">
                  {t('role.table.age')}
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider">
                  {t('role.table.gender')}
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider">
                  {t('role.table.status')}
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider">
                  {t('role.table.createTime')}
                </th>
                <th scope="col" className="px-6 py-3 text-left text-xs font-semibold uppercase tracking-wider">
                  {t('role.table.updateTime')}
                </th>
                <th scope="col" className="px-6 py-3 text-right text-xs font-semibold uppercase tracking-wider">
                  {t('role.table.actions')}
                </th>
                </tr>
              </thead>
              <tbody className="bg-white dark:bg-slate-800 divide-y divide-gray-200 dark:divide-slate-700 transition-colors">
              {filteredRoles.length > 0 ? (
                  filteredRoles.map((role) => (
                    <tr key={role.id} className="hover:bg-blue-500/15 dark:hover:bg-blue-400/15 transition-colors duration-150">
                      <td className="px-6 py-4 whitespace-nowrap">
                        <input
                          type="checkbox"
                          checked={selectedIds.includes(role.id)}
                          onChange={(e) => handleRowSelect(role.id, e.target.checked)}
                          className="h-4 w-4 text-blue-600 focus:ring-blue-500 border-gray-300 rounded"
                        />
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-900 dark:text-slate-100">
                        {role.id}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <div className="text-sm font-medium text-gray-900 dark:text-slate-100">{role.name}</div>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-slate-300">
                        {role.age}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${role.sex === '男' ? 'bg-blue-100 text-blue-800 dark:bg-blue-900/40 dark:text-blue-200' : 'bg-pink-100 text-pink-800 dark:bg-pink-900/40 dark:text-pink-200'}`}>
                          {getGenderLabel(role.sex)}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap">
                        <span className={`px-2 inline-flex text-xs leading-5 font-semibold rounded-full ${role.status === '启用' ? 'bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-200' : 'bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-200'}`}>
                          {getStatusLabel(role.status)}
                        </span>
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-slate-300">
                        {formatDateTime(role.createTime)}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-sm text-gray-500 dark:text-slate-300">
                        {formatDateTime(role.updateTime)}
                      </td>
                      <td className="px-6 py-4 whitespace-nowrap text-right text-sm font-medium">
                        <button
                          onClick={() => handleEdit(role.id)}
                          className="text-indigo-600 hover:text-indigo-900 mr-3 transition-colors duration-150"
                        >
                          {t('common.edit')}
                        </button>
                        <button
                          onClick={() => handleDelete(role.id)}
                          className="text-red-600 hover:text-red-900 transition-colors duration-150"
                        >
                          {t('common.delete')}
                        </button>
                      </td>
                    </tr>
                  ))
              ) : (
                <tr>
                  <td colSpan={9} className="px-6 py-12 text-center text-gray-500 dark:text-slate-400">
                    {t('role.empty')}
                  </td>
                </tr>
              )}
              </tbody>
            </table>
          )}
        </div>
        
        {/* 分页控件 */}
        {!loading && filteredRoles.length > 0 && (
          <div className="mt-6 flex justify-between items-center">
            <div className="text-sm text-gray-500 dark:text-slate-300">
              {t('common.totalRecords', { count: filteredRoles.length })}
            </div>
            <div className="flex items-center space-x-1">
              <button
                onClick={() => fetchRoles(1)}
                disabled={currentPage === 1}
                className={`px-3 py-1 rounded border ${currentPage === 1 ? 'border-gray-200 bg-gray-50 text-gray-400 cursor-not-allowed dark:border-slate-700 dark:bg-slate-700 dark:text-slate-500' : 'border-gray-300 hover:bg-gray-50 dark:border-slate-600 dark:hover:bg-slate-700 dark:text-slate-100'}`}
              >
                {t('common.firstPage')}
              </button>
              <button
                onClick={() => fetchRoles(currentPage - 1)}
                disabled={currentPage === 1}
                className={`px-3 py-1 rounded border ${currentPage === 1 ? 'border-gray-200 bg-gray-50 text-gray-400 cursor-not-allowed dark:border-slate-700 dark:bg-slate-700 dark:text-slate-500' : 'border-gray-300 hover:bg-gray-50 dark:border-slate-600 dark:hover:bg-slate-700 dark:text-slate-100'}`}
              >
                {t('common.prevPage')}
              </button>
              <span className="text-sm text-gray-700 dark:text-slate-200 px-2">
                {t('common.pageIndicator', { page: currentPage })}
              </span>
              
              {/* 页码按钮 */}
              {(() => {
                const totalPages = Math.ceil(totalCount / pageSize);
                const pages = [];
                
                // 生成页码数组
                for (let i = 1; i <= totalPages; i++) {
                  // 只显示首页、末页和当前页附近的页码
                  if (i === 1 || i === totalPages || (i >= currentPage - 1 && i <= currentPage + 1)) {
                    pages.push(i);
                  }
                }
                
                return pages.map((page, index) => {
                  const prevPage = index > 0 ? pages[index - 1] : 0;
                  const showEllipsis = index > 0 && page > prevPage + 1;
                  
                  return (
                    <React.Fragment key={page}>
                      {showEllipsis && <span className="px-2 text-gray-500 dark:text-slate-400">...</span>}
                      <button
                        onClick={() => fetchRoles(page)}
                        className={`px-3 py-1 rounded border ${currentPage === page ? 'border-blue-500 bg-blue-50 text-blue-600 dark:border-blue-400 dark:bg-blue-500/10 dark:text-blue-200' : 'border-gray-300 hover:bg-gray-50 dark:border-slate-600 dark:hover:bg-slate-700 dark:text-slate-100'}`}
                      >
                        {page}
                      </button>
                    </React.Fragment>
                  );
                });
              })()}
              
              <button
                onClick={() => fetchRoles(currentPage + 1)}
                disabled={currentPage >= Math.ceil(totalCount / pageSize)}
                className={`px-3 py-1 rounded border ${currentPage >= Math.ceil(totalCount / pageSize) ? 'border-gray-200 bg-gray-50 text-gray-400 cursor-not-allowed dark:border-slate-700 dark:bg-slate-700 dark:text-slate-500' : 'border-gray-300 hover:bg-gray-50 dark:border-slate-600 dark:hover:bg-slate-700 dark:text-slate-100'}`}
              >
                {t('common.nextPage')}
              </button>
              <button
                onClick={() => fetchRoles(Math.ceil(totalCount / pageSize))}
                disabled={currentPage >= Math.ceil(totalCount / pageSize)}
                className={`px-3 py-1 rounded border ${currentPage >= Math.ceil(totalCount / pageSize) ? 'border-gray-200 bg-gray-50 text-gray-400 cursor-not-allowed dark:border-slate-700 dark:bg-slate-700 dark:text-slate-500' : 'border-gray-300 hover:bg-gray-50 dark:border-slate-600 dark:hover:bg-slate-700 dark:text-slate-100'}`}
              >
                {t('common.lastPage')}
              </button>
            </div>
          </div>
        )}
      </div>

      {/* 新增弹出框 - 轻微模糊背景，可清楚看到下方页面文字 */}
      {isAddModalOpen && (
        <div className="fixed inset-0 backdrop-blur-xs flex items-center justify-center z-50">
          <div className="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6 max-w-md w-full border border-gray-100 dark:border-slate-700 transition-all duration-300 hover:shadow-xl">
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-lg font-medium text-gray-900 dark:text-slate-100">{t('role.modal.createTitle')}</h3>
              <button
                onClick={handleCloseAddModal}
                className="text-gray-400 hover:text-gray-500 dark:text-slate-400 dark:hover:text-slate-200 focus:outline-none"
              >
                <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
              
            <div className="space-y-4">
              <div>
                <label htmlFor="name" className="block text-sm font-medium text-gray-700 dark:text-slate-200 mb-1">
                  {t('role.name')}
                </label>
                <input
                  type="text"
                  id="name"
                  name="name"
                  value={newRoleData.name}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 dark:focus:border-slate-500 bg-white dark:bg-slate-700 text-gray-900 dark:text-slate-100"
                  placeholder={t('role.namePlaceholder')}
                />
              </div>
              
              <div>
                <label htmlFor="age" className="block text-sm font-medium text-gray-700 dark:text-slate-200 mb-1">
                  {t('role.table.age')}
                </label>
                <input
                  type="number"
                  id="age"
                  name="age"
                  value={newRoleData.age}
                  onChange={(e) => setNewRoleData(prev => ({ ...prev, age: parseInt(e.target.value) || 0 }))}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 dark:focus:border-slate-500 bg-white dark:bg-slate-700 text-gray-900 dark:text-slate-100"
                  min="0"
                  placeholder={t('role.agePlaceholder')}
                />
              </div>
              
              <div>
                <label htmlFor="sex" className="block text-sm font-medium text-gray-700 dark:text-slate-200 mb-1">
                  {t('role.table.gender')}
                </label>
                <select
                  id="sex"
                  name="sex"
                  value={newRoleData.sex}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 dark:focus:border-slate-500 bg-white dark:bg-slate-700 text-gray-900 dark:text-slate-100"
                >
                  <option value="男">{t('role.gender.male')}</option>
                  <option value="女">{t('role.gender.female')}</option>
                </select>
              </div>
              
              <div>
                <label htmlFor="status" className="block text-sm font-medium text-gray-700 dark:text-slate-200 mb-1">
                  {t('role.table.status')}
                </label>
                <select
                  id="status"
                  name="status"
                  value={newRoleData.status}
                  onChange={handleInputChange}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 dark:focus:border-slate-500 bg-white dark:bg-slate-700 text-gray-900 dark:text-slate-100"
                >
                  <option value="启用">{t('role.status.enabled')}</option>
                  <option value="禁用">{t('role.status.disabled')}</option>
                </select>
              </div>
            </div>
            
            <div className="mt-6 flex justify-end space-x-3">
              <button
                onClick={handleCloseAddModal}
                className="px-4 py-2 border border-gray-300 dark:border-slate-600 rounded-md shadow-sm text-sm font-medium text-gray-700 dark:text-slate-200 bg-white bg-opacity-80 dark:bg-slate-700 dark:bg-opacity-80 hover:bg-gray-50 dark:hover:bg-slate-600 transition-colors duration-150"
              >
                {t('common.cancel')}
              </button>
              <button
                onClick={handleSubmitAdd}
                className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 bg-opacity-90 hover:bg-blue-700 transition-colors duration-150"
              >
                {t('common.confirm')}
              </button>
            </div>
          </div>
        </div>
      )}
      
      {/* 编辑弹出框 */}
      {isEditModalOpen && (
        <div className="fixed inset-0 backdrop-blur-xs flex items-center justify-center z-50">
          <div className="bg-white dark:bg-slate-800 rounded-xl shadow-lg p-6 max-w-md w-full border border-gray-100 dark:border-slate-700 transition-all duration-300 hover:shadow-xl">
            <div className="flex justify-between items-center mb-4">
              <h3 className="text-lg font-medium text-gray-900 dark:text-slate-100">{t('role.modal.editTitle')}</h3>
              <button
                onClick={handleCloseEditModal}
                className="text-gray-400 hover:text-gray-500 dark:text-slate-400 dark:hover:text-slate-200 focus:outline-none"
              >
                <svg xmlns="http://www.w3.org/2000/svg" className="h-6 w-6" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                </svg>
              </button>
            </div>
              
            <div className="space-y-4">
              <div>
                <label htmlFor="edit-name" className="block text-sm font-medium text-gray-700 dark:text-slate-200 mb-1">
                  {t('role.name')}
                </label>
                <input
                  type="text"
                  id="edit-name"
                  name="name"
                  value={editRoleData.name}
                  onChange={handleEditInputChange}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 dark:focus:border-slate-500 bg-white dark:bg-slate-700 text-gray-900 dark:text-slate-100"
                  placeholder={t('role.namePlaceholder')}
                />
              </div>
              
              <div>
                <label htmlFor="edit-age" className="block text-sm font-medium text-gray-700 dark:text-slate-200 mb-1">
                  {t('role.table.age')}
                </label>
                <input
                  type="number"
                  id="edit-age"
                  name="age"
                  value={editRoleData.age}
                  onChange={handleEditAgeChange}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 dark:focus:border-slate-500 bg-white dark:bg-slate-700 text-gray-900 dark:text-slate-100"
                  min="0"
                  placeholder={t('role.agePlaceholder')}
                />
              </div>
              
              <div>
                <label htmlFor="edit-sex" className="block text-sm font-medium text-gray-700 dark:text-slate-200 mb-1">
                  {t('role.table.gender')}
                </label>
                <select
                  id="edit-sex"
                  name="sex"
                  value={editRoleData.sex}
                  onChange={handleEditInputChange}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 dark:focus:border-slate-500 bg-white dark:bg-slate-700 text-gray-900 dark:text-slate-100"
                >
                  <option value="男">{t('role.gender.male')}</option>
                  <option value="女">{t('role.gender.female')}</option>
                </select>
              </div>
              
              <div>
                <label htmlFor="edit-status" className="block text-sm font-medium text-gray-700 dark:text-slate-200 mb-1">
                  {t('role.table.status')}
                </label>
                <select
                  id="edit-status"
                  name="status"
                  value={editRoleData.status || '启用'}
                  onChange={handleEditInputChange}
                  className="w-full px-3 py-2 border border-gray-300 dark:border-slate-600 rounded-md shadow-sm focus:outline-none focus:ring-blue-500 focus:border-blue-500 dark:focus:border-slate-500 bg-white dark:bg-slate-700 text-gray-900 dark:text-slate-100"
                >
                  <option value="启用">{t('role.status.enabled')}</option>
                  <option value="禁用">{t('role.status.disabled')}</option>
                </select>
              </div>
            </div>
            
            <div className="mt-6 flex justify-end space-x-3">
              <button
                onClick={handleCloseEditModal}
                className="px-4 py-2 border border-gray-300 dark:border-slate-600 rounded-md shadow-sm text-sm font-medium text-gray-700 dark:text-slate-200 bg-white bg-opacity-80 dark:bg-slate-700 dark:bg-opacity-80 hover:bg-gray-50 dark:hover:bg-slate-600 transition-colors duration-150"
              >
                {t('common.cancel')}
              </button>
              <button
                onClick={handleSubmitEdit}
                className="px-4 py-2 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-blue-600 bg-opacity-90 hover:bg-blue-700 transition-colors duration-150"
              >
                {t('common.save')}
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default RoleManage
